package com.wkq.util

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.core.app.ActivityCompat

/**
 *
 *@Author: wkq
 *
 *@Time: 2025/8/27 9:28
 *
 *@Desc:   获取定位地址
 */

class NativeLocationSingleHelper(
    private val context: Context, private val timeout: Long = 5000L, // 默认5秒超时
    private val callback: (location: Location?) -> Unit

) : LocationListener {

    private val locationManager =
        context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    private var isStartLocation = false
    private val handler = Handler(Looper.getMainLooper())
    private var timeoutRunnable: Runnable? = null

    // 两次位置更新的最小时间间隔 0，表示不限制时间，只要位置有变化就立刻回调（但可能非常耗电）
    val minTimeMs = 0L

    // 两次位置更新的最小位移距离 0f，表示不限制距离变化，只要时间满足就触发 1–5 米 → 高精度运动跟踪
    val minDistanceM = 0f

    val PRECISION_LAT: Double = 0.00009 // 纬度约 10 米

    val PRECISION_LON: Double = 0.00012 // 经度约 10 米

    /**
     *开启定位
     */
    @SuppressLint("MissingPermission")
    fun startLocation() {
        MethodLogger.logMethod()
        if (isStartLocation) return
        if (!hasPermission()) {
            throw SecurityException("需要 ACCESS_FINE_LOCATION 或 ACCESS_COARSE_LOCATION 权限")
        }
        getSingleGpsLocation()
        getSingleNetLocation()

        //超时返回缓存定位
        timeoutRunnable = Runnable { getCacheLocation() }
        // 设置超时回调
        handler.postDelayed(timeoutRunnable!!, timeout)

    }

    /**
     *释放
     */

    fun release() {
        locationManager.removeUpdates(this)
        timeoutRunnable?.let {
            handler.removeCallbacks(it)
        }

    }


    /**
     * 单次获取网络定位
     */
    @SuppressLint("MissingPermission")
    fun getSingleNetLocation() {
        MethodLogger.logMethod()
        if (!hasPermission()) return
        if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            locationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, minTimeMs, minDistanceM, this
            )
        }
    }


    /**
     * 单次获取GPS定位
     */
    @SuppressLint("MissingPermission")
    fun getSingleGpsLocation() {
        MethodLogger.logMethod()
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, minTimeMs, minDistanceM, this
            )
        }
    }

    fun getCacheLocation() {
        MethodLogger.logMethod()
        val lastLocation = getLastKnownLocation()
        callback(lastLocation)
    }

    private fun hasPermission(): Boolean {
        return ActivityCompat.checkSelfPermission(
            context, Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(
            context, Manifest.permission.ACCESS_COARSE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
    }

    @SuppressLint("MissingPermission")
    private fun getLastKnownLocation(): Location? {
        MethodLogger.logMethod()
        val providers = locationManager.getProviders(true)
        var bestLocation: Location? = null
        for (provider in providers) {
            val l = locationManager.getLastKnownLocation(provider) ?: continue
            if (bestLocation == null || l.accuracy < bestLocation.accuracy) {
                bestLocation = l
            }
        }
        return bestLocation
    }


    override fun onLocationChanged(location: Location) {

        timeoutRunnable?.let { handler.removeCallbacks(it) }
        processLocation(location)
        isStartLocation = false

    }

    var oldLatitude: Double = 0.0
    var oldLongitude: Double = 0.0

    /**
     * 处理定位信息
     */
    private fun processLocation(location: Location?) {
        val latitude: Double
        val longitude: Double
        var newLocation: Location? = null
        if (location == null) {
            newLocation = Location("默认 ")
            latitude = 39.9042 // 北京
            longitude = 116.4074
            newLocation.latitude = latitude
            newLocation.longitude = longitude
        } else {
            newLocation= location
            latitude = location.getLatitude()
            longitude = location.getLongitude()
            locationManager.removeUpdates(this)
        }

        Log.d("定位状态:", "提供者:" + newLocation.provider + "纬度:" + latitude + ", 经度:" + longitude)
//        if (Math.abs(latitude - oldLatitude) < PRECISION_LAT && Math.abs(longitude - oldLongitude) < PRECISION_LON) {
//            return;
//        }
        callback(newLocation)


        oldLatitude = latitude
        oldLongitude = longitude


    }

    override fun onLocationChanged(locations: List<Location?>) {

        timeoutRunnable?.let {
            handler.removeCallbacks(it)
        }
        var location: Location? = null
        if (locations == null) {
            processLocation(null)
        } else {
            location = locations[0]
            processLocation(location)
        }
        isStartLocation = false

    }

    override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
        Log.d("定位状态:", "提供者:" + provider)
    }

    override fun onProviderEnabled(provider: String) {
        Log.d("定位状态:", "提供者:" + provider + ":onProviderEnabled")
    }

    override fun onProviderDisabled(provider: String) {
        Log.d("定位状态:", "提供者:" + provider + ":onProviderDisabled")
    }


}